package com.nic.view.widget;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;

import com.nic.view.R;
import com.nic.view.util.DateTimeUtil;
import com.nic.view.util.JToast;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/***********************************************************************
 * * 版权所有： Copyright (C) 2006-2016 聚进科技有限公司.
 * * 作者：刘伟杰
 * * 创始时间：2016/7/28 15:58
 * * 修改人：刘伟杰
 * * 修改时间：2016/7/28 15:58
 * * 描述：
 * *
 ************************************************************************/
@SuppressLint("SimpleDateFormat")
public class CalendarViewDialog extends Dialog implements OnClickListener {
    public static final int CORRECT_TO_MINTE_1ST = 0;
    public static final int CORRECT_TO_DAY_1ST = 1;
    public static final int SHOW_HOUR_MINUTE_1ST = 2;
    private CalendarView calendar;
    private ImageButton calendarLeft;
    private TextView calendarCenter;
    private ImageButton calendarRight;
    private Context context;
    private View dialogView;
    private TimePicker timePicker;
    private Button btnCancel, btnConfirm;
    private OnBtnClickListener onBtnClickListener;
    private int style;
    // 默认日期
    private int year, month, day = getDefaultDay(), hourOfDay, minute;


    public static final int DefferentStyte = 0;
    public static final int JustShowBeforeDay = 1;
    public static final int JUSTSHOWAFTERDAY = 2;
    private int CurrentStyte = DefferentStyte;

    public void setCurrentStyte(int currentStyte) {
        CurrentStyte = currentStyte;
    }


    // 重载构造
    public CalendarViewDialog(Context context, int style) {
        // 设置上下文对象 和 dialog属性
        super(context, R.style.dialog_no_bg);
        // 赋值
        this.context = context;
        this.style = style;
        // 初始化方法
        init(context);
        // 加载对话框文件
        this.setContentView(dialogView);
        setDialogSize(context);
    }

    public CalendarViewDialog(Context context, int style, String s) {
        // 设置上下文对象 和 dialog属性
        super(context, R.style.dialog_no_bg);
        // 赋值
        this.context = context;
        this.style = style;
        // 初始化方法
        init(context);
        // 加载对话框文件
        this.setContentView(dialogView);
        if (!TextUtils.isEmpty(s)) {
            Date timeFromString = DateTimeUtil.getTimeFromString(DateTimeUtil.FORMAT_DATE, s);
            setCurDate(timeFromString);
        }
        setDialogSize(context);
    }

    private void setDialogSize(Context context) {
        Window window = getWindow();
        window.setGravity(Gravity.CENTER);
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = dm.widthPixels;
        lp.height = dm.heightPixels / 2;
        window.setAttributes(lp);
    }

    public void setCurDate(Date curDate) {
        calendar.setCurDate(curDate);
        calendar.invalidate();
    }

    /**
     * 初始化方法
     *
     * @param context
     */
    public void init(final Context context) {
        // 设置电价对坏框外部不能取消
        this.setCanceledOnTouchOutside(true);
        dialogView = LayoutInflater.from(context).inflate(
                R.layout.k_dialog_calendarview, null);
        // 获取日历控件对象
        calendar = (CalendarView) dialogView.findViewById(R.id.calendar);
        calendarLeft = (ImageButton) dialogView.findViewById(R.id.calendarLeft);
        calendarCenter = (TextView) dialogView
                .findViewById(R.id.calendarCenter);
        calendarRight = (ImageButton) dialogView
                .findViewById(R.id.calendarRight);
        timePicker = (TimePicker) dialogView.findViewById(R.id.timePicker);
        // 设置默认分钟为零
        timePicker.setCurrentMinute(0);
        btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
        btnConfirm = (Button) dialogView.findViewById(R.id.btnConfirm);
        calendar.setSelectMore(false); // 单选
        // 获取日历中年月 ya[0]为年，ya[1]为月（格式大家可以自行在日历控件中改）
        String[] ya = calendar.getYearAndmonth().split("-");
        // 获取年月日
        year = Integer.parseInt(ya[0]);
        month = Integer.parseInt(ya[1]);
        calendarCenter.setText(ya[0] + "年" + ya[1] + "月");
        calendarLeft.setOnClickListener(this);
        calendarRight.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        // 设置显示样式
        setDialogModel(style);
        // 设置控件监听，可以监听到点击的每一天（大家也可以在控件中根据需求设定）
        calendar.setOnItemClickListener(new CalendarView.OnItemClickListener() {
            @Override
            public void OnItemClick(Date selectedStartDate,
                                    Date selectedEndDate, Date downDate) {
                Calendar c = Calendar.getInstance();
                c.setTime(downDate);
                year = c.get(Calendar.YEAR);
                month = c.get(Calendar.MONTH) + 1;
                day = c.get(Calendar.DATE);
                calendarCenter.setText(year + "年" + month + "月");
                //  确认按钮点击时间
                if (CurrentStyte == JustShowBeforeDay) {
                    // 判断
                    String date1 = getCalendarDate("yyyy-MM-dd");
                    String date2 = DateTimeUtil.getSystemDate();
                    if (DateTimeUtil.timeCompare(date1, date2) > 0) {
                        JToast.show(context, "不能选择大于今天的日期", 1);
                        return;
                    } else {
                        onBtnClickListener.onClick(dialogView);
                        dismiss();
                        return;
                    }
                } else if (CurrentStyte == JUSTSHOWAFTERDAY) {
                    // 判断
                    String date1 = getCalendarDate("yyyy-MM-dd");
                    String date2 = DateTimeUtil.getSystemDate();
                    if (DateTimeUtil.timeCompare(date1, date2) < 0) {
                        JToast.show(context, "不能选择小于今天的日期", 1);
                    } else {
                        onBtnClickListener.onClick(dialogView);
                        dismiss();
                    }
                    return;
                } else {
                    onBtnClickListener.onClick(dialogView);
                    dismiss();
                }
                return;
            }
        });
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.calendarLeft) {// 点击上一月 同样返回年月
            String leftYearAndmonth = calendar.clickLeftMonth();
            String[] ya1 = leftYearAndmonth.split("-");
            calendarCenter.setText(ya1[0] + "年" + ya1[1] + "月");

        } else if (i == R.id.calendarRight) {// 点击下一月
            String rightYearAndmonth = calendar.clickRightMonth();
            String[] ya2 = rightYearAndmonth.split("-");
            calendarCenter.setText(ya2[0] + "年" + ya2[1] + "月");

        } else if (i == R.id.btnCancel) {// 对话框销毁
            dismiss();

        } else if (i == R.id.btnConfirm) {// 接口传递参数
            if (CurrentStyte == JustShowBeforeDay) {
                // 判断
                String date1 = getCalendarDate("yyyy-MM-dd");
                String date2 = DateTimeUtil.getSystemDate();
                if (DateTimeUtil.timeCompare(date1, date2) > 0) {
                    JToast.show(context, "不能选择大于今天的日期", 1);
                } else {
                    onBtnClickListener.onClick(v);
                    dismiss();
                }
            } else if (CurrentStyte == JUSTSHOWAFTERDAY) {
                // 判断
                String date1 = getCalendarDate("yyyy-MM-dd");
                String date2 = DateTimeUtil.getSystemDate();
                if (DateTimeUtil.timeCompare(date1, date2) < 0) {
                    JToast.show(context, "不能选择小于今天的日期", 1);
                } else {
                    onBtnClickListener.onClick(v);
                    dismiss();
                }
            } else {
                onBtnClickListener.onClick(v);
                dismiss();
            }

        } else {
        }

    }

    /**
     * 定义接口传递参试
     */
    public interface OnBtnClickListener {
        void onClick(View v);
    }

    /**
     * 设置监听方法
     */
    public void setOnBtnClickListener(OnBtnClickListener onBtnClickListener) {
        this.onBtnClickListener = onBtnClickListener;
    }

    /**
     * 获取日期yyyy-MM-dd HH:mm
     */
    public String getCalendarDate(String format) {
        hourOfDay = timePicker.getCurrentHour();
        minute = timePicker.getCurrentMinute();
        // 获得日历实例
        Calendar calendar = Calendar.getInstance();
        // 设置参数
        calendar.set(year, month - 1, day, hourOfDay, minute);
        // 日期转化
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        // 转化
        return sdf.format(calendar.getTime());
    }

    /**
     * 获取当前日期
     */
    private int getDefaultDay() {
        // 获取当前时间
        Calendar c = Calendar.getInstance();
        return c.get(Calendar.DATE);
    }

    /**
     * 设置显示样式
     */
    private void setDialogModel(int style) {
        if (style == CORRECT_TO_MINTE_1ST) {
            calendar.setVisibility(View.VISIBLE);
            timePicker.setVisibility(View.VISIBLE);
        } else if (style == CORRECT_TO_DAY_1ST) {
            calendar.setVisibility(View.VISIBLE);
            timePicker.setVisibility(View.GONE);
        } else if (style == SHOW_HOUR_MINUTE_1ST) {
            calendar.setVisibility(View.GONE);
            timePicker.setVisibility(View.VISIBLE);

        }

    }
}
